package com.sbr.esbmonitor.camel.route;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sbr.esbmonitor.camel.model.Endpoint;
import com.sbr.esbmonitor.camel.model.Route;

public class RouteDescriptionParser {

	/*
	 * Endpoint[timer://myTimer?fixedRate=true&period=2000] -> Instrumentation:route[UnitOfWork(Channel[sendTo(Endpoint[nmr://ExampleRouter])])";
	 */

	private String routeString;
	private Route route;
	private List<Endpoint> endpoints;
	private EndpointParser endpointParser;

	public RouteDescriptionParser(String routeString) {
		this.routeString = routeString;
		endpointParser = new EndpointParser();
		route = new Route();
	}

	public void parse() {
		parseFrom();
		parseEndpoints();
	}

	public void parseFrom() {
		Pattern ENDPOINT_PATTERN = Pattern.compile("Endpoint\\[(.*?)\\]");

		Matcher m = ENDPOINT_PATTERN.matcher(routeString);
		m.find();
		String endpoint = m.group(1);
		System.out.println("From found : "+endpoint);
		route.setFrom(endpointParser.parse(endpoint));
	}

	public void parseEndpoints() {

		Pattern ENDPOINT_PATTERN = Pattern.compile("Endpoint\\[(.*?)\\]");

		Matcher m = ENDPOINT_PATTERN.matcher(routeString);
		endpoints = new ArrayList<Endpoint>();
		while (m.find()) {
			String endpoint = m.group(1);
			System.out.println("Endpoint found : "+endpoint);
			endpoints.add(endpointParser.parse(endpoint));
		}

	}

	@Deprecated
	public void parseEndpointsOld() {

		if (routeString.contains("Endpoint[")) {
			routeString = routeString.substring(routeString.indexOf("Endpoint["));
			routeString = routeString.substring("Endpoint[".length(), routeString.indexOf("]"));
			endpoints = endpointParser.parse(routeString.split(","));
		} else {
			endpoints = new ArrayList<Endpoint>();
		}

	}

	public List<Endpoint> getEndpoints() {
		return endpoints;
	}

	public void setEndpointParser(EndpointParser endpointParser) {
		this.endpointParser = endpointParser;
	}

	public Route getRoute() {
		return route;
	}
	
}
